package util;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;

import org.apache.commons.io.FilenameUtils;
import org.apache.myfaces.custom.fileupload.UploadedFile;

public class MyHelper {

	public static boolean UploadFile(UploadedFile upFile, String nowTime, String pathName) {
		System.out.println("Submitting File..!! ");
		//String fileName = FilenameUtils.getName(upFile.getName());
		//String contentType = upFile.getContentType();
		byte[] bytes = null;
		try {
			bytes = upFile.getBytes();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}

		// ------------
		ExternalContext externalContext = FacesContext.getCurrentInstance()
				.getExternalContext();
		ServletContext servletContext = (ServletContext) externalContext
				.getContext();

		FileOutputStream fileOut;
		try {
			String path = servletContext.getRealPath(pathName + nowTime
					+ upFile.getName());
			System.out.println(path);

			fileOut = new FileOutputStream(path);
			fileOut.write(bytes, 0, bytes.length);
			fileOut.flush();
			fileOut.close();

			System.out.println(fileOut.toString());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		// --------------------
		System.out.println("SubmitFile complete..!!");
		return true;
	}
}
